package com.fjnu.service.impl;

import com.fjnu.dao.UserDao;
import com.fjnu.entity.User;
import com.fjnu.dto.UserConditionDto;
import com.fjnu.dto.PageResult;
import com.fjnu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User queryByName(String username) {
        try {
            UserConditionDto condition = new UserConditionDto();
            condition.setUsername(username);
            List<User> users = userDao.selectByCondition(condition);
            return users.isEmpty() ? null : users.get(0);
        } catch (Exception e) {
            log.error("查询用户失败: {}", e.getMessage());
            throw new RuntimeException("查询用户失败", e);
        }
    }

    @Override
    @Transactional
    public int register(User user) {
        try {
            // 检查用户名是否已存在
            User existingUser = queryByName(user.getUsername());
            if (existingUser != null) {
                return 0; // 用户名已存在
            }

            int result = userDao.insert(user);
            return result > 0 ? 1 : 0;
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage());
            throw new RuntimeException("用户注册失败", e);
        }
    }

    @Override
    public PageResult queryUsers(UserConditionDto userCondition, Integer pageNum, Integer pageSize) {
        try {
            if (pageNum == null || pageNum < 1) pageNum = 1;
            if (pageSize == null || pageSize < 1) pageSize = 10;

            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = pageNum * pageSize;

            List<User> users = userDao.selectByConditionWithLimit(userCondition, startIndex, endIndex);
            int total = userDao.countByCondition(userCondition);

            return new PageResult<>(users, total, pageNum, pageSize);
        } catch (Exception e) {
            log.error("查询用户列表失败: {}", e.getMessage());
            throw new RuntimeException("查询用户列表失败", e);
        }
    }

    @Override
    @Transactional
    public void addAssignRole(String userId, List roleIds) {
        try {
            Integer userIdInt = Integer.parseInt(userId);

            // 批量插入用户角色关系
            for (Object roleIdObj : roleIds) {
                Integer roleId = Integer.parseInt(roleIdObj.toString());
                userDao.insertUserRole(userIdInt, roleId);
            }
        } catch (Exception e) {
            log.error("分配用户角色失败: {}", e.getMessage());
            throw new RuntimeException("分配用户角色失败", e);
        }
    }

    @Override
    public User login(String username, String password) {
        try {
            return userDao.selectByNameAndPwd(username, password);
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage());
            throw new RuntimeException("用户登录失败", e);
        }
    }

    @Override
    @Transactional
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        try {
            // 验证旧密码
            User user = userDao.selectById(userId);
            if (user == null || !user.getPassword().equals(oldPassword)) {
                return false;
            }

            int result = userDao.updatePassword(userId, newPassword);
            return result > 0;
        } catch (Exception e) {
            log.error("修改密码失败: {}", e.getMessage());
            throw new RuntimeException("修改密码失败", e);
        }
    }
}